package com.tan.kotlintest.countdownlatch

import android.os.Handler
import android.os.Message
import android.view.View
import com.tan.kotlintest.R
import com.tan.kotlintest.base.BaseActivity
import com.tan.kotlintest.util.LogUtil
import kotlinx.android.synthetic.main.activity_test_count_down_latch_layout.*
import java.lang.ref.WeakReference
import java.util.concurrent.CountDownLatch

/*
 * Copyright (C) 2018 重庆一聊高科技有限公司
 * 版权所有
 *
 * 功能描述：测试CountDownLatch 同步辅助类 - 应用场景: 一个子thread等待UI线程更新状态后才可以使用
 * 作者：txj
 * 创建时间：2019/2/18
 *
 * 修改人：
 * 修改描述：
 * 修改日期
 */
class TestCountDownLatchActivity : BaseActivity() {

    private val mHandler = TimeHandler(this)
    private var mCountDownLatch = CountDownLatch(1)
    private var GET_TEST_MSG = 0x11

    override fun getContentView(): View? {
        return inflate(R.layout.activity_test_count_down_latch_layout)
    }

    override fun onContentAdded() {
        setTitleText("测试CountDownLatch同步辅助类")
        test_tv.setOnClickListener { testThread() }
    }

    /**
     * 开启线程,delay发送消息通知主线程更新
     * 主线程更新完成后,子线程更新
     */
    private fun testThread() {
        Thread(Runnable {
            try {
                LogUtil.i("子线程开始")
                mHandler.sendEmptyMessageDelayed(GET_TEST_MSG, 2000)
                mCountDownLatch.await()
                LogUtil.i("子线程等待UI线程更新后才可以使用")
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
        }).start()
    }

    private class TimeHandler internal constructor(settingActivity: TestCountDownLatchActivity) : Handler() {

        private val mSettingActivityWeakReference: WeakReference<TestCountDownLatchActivity> = WeakReference(settingActivity)

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val settingActivity = mSettingActivityWeakReference.get()
            if (!settingActivity!!.isFinishing) {
                if (msg.what == settingActivity.GET_TEST_MSG) {
                    LogUtil.i("主线程更新")
                    settingActivity.mCountDownLatch.countDown()
                }
            }
        }
    }


}